//
//  RecommendDetailController.m
//  Tang
//
//  Created by 邓芮 on 15/12/9.
//  Copyright © 2015年 352324497@qq.com. All rights reserved.
//

#import "RecommendDetailController.h"
#import "CollectionDetailTableViewCell.h"
#import "ShopTableViewCell.h"
#import "UserInfoCell.h"
#import "CommentView.h"
#import "CommentsViewController.h"
#import "CollectionDetailCellModel.h"
#import "WebViewController.h"
#import "UMSocial.h"
#import "BmobModel.h"
#import <BmobSDK/BmobFile.h>
@interface RecommendDetailController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) CollectionDetailCellModel *model;
@property (nonatomic, strong) NSMutableArray *commentsArray;

@end
static NSString *firstCellIdentifier = @"cell1";
static NSString *secondCellIdentifier = @"cell2";
static NSString *userCellIdentifier = @"cell3";
@implementation RecommendDetailController


- (void)viewWillAppear:(BOOL)animated
{
    [self findAllCommentsData:100];
    
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self requestCell];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KWidth, KHeight - 64) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = NO;
    [self.tableView registerClass:[CollectionDetailTableViewCell class] forCellReuseIdentifier:firstCellIdentifier];
    [self.tableView registerClass:[ShopTableViewCell class] forCellReuseIdentifier:secondCellIdentifier];
    [self.tableView registerClass:[UserInfoCell class] forCellReuseIdentifier:userCellIdentifier];
    [self.view addSubview:self.tableView];
    
    UIButton *rightBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 25, 25);
    [rightBtn setImage:[UIImage imageNamed:@"share"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(rightBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem=[[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem=rightItem;
    
   
    
 
}
- (void)findAllCommentsData:(NSInteger)limit
{
    BmobQuery *bquery = [BmobQuery queryWithClassName:[NSString stringWithFormat:@"Comments%@",_Id]];
    [bquery orderByDescending:@"createdAt"];
    bquery.limit = limit;
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error)
    {
        if (error)
        {
            NSLog(@"error:%@",error);
//            [CallTool alertActionWithTitle:@"提示" message:@"好像评论没有成功哦!可能网络很差!" other:@"取消" uiViewController:self];
        }
        else
        {
            self.commentsArray = [NSMutableArray array];
            for (BmobObject *obj in array)
            {
                UserModel *model = [[UserModel alloc] init];
                model.username = [obj objectForKey:@"userName"];
                model.conent = [obj objectForKey:@"userComments"];
                BmobQuery *bquery = [BmobQuery queryWithClassName:@"_User"];
                model.time = [obj objectForKey:@"createdAt"];
                [bquery getObjectInBackgroundWithId:[obj objectForKey:@"author"] block:^(BmobObject *object, NSError *error)
                {
                    [[NetworkState shareInstance] reachablityStatesWithDongHua:self];
                    BmobFile *file = [object objectForKey:@"headerImage"];
                    model.avatar = file.url;
                    
                    [self.commentsArray addObject:model];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        [self.tableView reloadData];
                        [[NetworkState shareInstance] finshYYToVc:self];
                    }) ;
                    
                }];
                
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.tableView reloadData];
//            [[NetworkState shareInstance] finshYYToVc:self];
        }) ;

    }];
    
}


- (void)requestCell
{
    [[NetworkState shareInstance] reachablityStatesWithDongHua:self];
    NSString *string = [NSString stringWithFormat:@"app_installtime=1449036721.708244&app_versions=5.0.1&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&id=%@&oauth_token=c6ed8d108659f067da486970ca4b3aad&os_versions=9.1&screensize=640&track_deviceid=724D868E-D23A-4A92-902C-909AB20FB585&v=8", self.Id];
    NSURL *url = [NSURL URLWithString:@"http://open3.bantangapp.com/community/post/info"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[string dataUsingEncoding:NSUTF8StringEncoding]];
    [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data == nil)
        {
            UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"提示" message:@"亲, 网络好像不是很给力哦~~~" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *OKaction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }];
            [alertView addAction:OKaction];
            [self presentViewController:alertView animated:YES completion:nil];
            return;
        }
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        self.model = [CollectionDetailCellModel JsonWithDetailDic:dic];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            [[NetworkState shareInstance] finshYYToVc:self];
        });
    }] resume];
}


#pragma mark -- 发表事件 --
- (void)publish:(UITapGestureRecognizer *)tap
{
    CommentsViewController *recomment = [[CommentsViewController alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:recomment];
    recomment.indentierId = _Id;
    [self presentViewController:nav animated:NO completion:nil];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.model != nil)
    {
        if (section == 0)
        {
            return 1;
        }
        else if (section == 1)
        {
            return 1;
        }
        else
        {
            return self.commentsArray.count;
        }
    }
    return 0;
  
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0)
    {
        CollectionDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:firstCellIdentifier forIndexPath:indexPath];
//        cell.model = self.model;
        [cell setModel:self.model tag:2000];
       
        [cell.comment addTarget:self action:@selector(commentAction:) forControlEvents:UIControlEventTouchUpInside];
        
        
        
        [cell.like addTarget:self action:@selector(likeAction:) forControlEvents:UIControlEventTouchUpInside];
        
        return cell;
    }
    else if (indexPath.section == 1)
    {
        ShopTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:secondCellIdentifier forIndexPath:indexPath ];
        if (self.model.productArray.count != 0)
        {
            cell.model = self.model.productArray[indexPath.row];
        }
        return cell;
    }
    else
    {
        UserInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:userCellIdentifier];
        cell.selectionStyle = NO;
        cell.model = self.commentsArray[indexPath.row];
        return cell;
    }
    
}

#pragma mark  ---cell 上button事件 ---

- (void)commentAction:(DIYButton *)btn
{
    BmobUser *bUser = [BmobUser getCurrentUser];
    if (bUser)
    {
    CommentsViewController *recomment = [[CommentsViewController alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:recomment];
    recomment.indentierId = _Id;
    [self presentViewController:nav animated:NO completion:nil];
        
    }
    else
    {
        [CallTool alertActionWithTitle:@"提示" message:@"还没有登陆哦,请先登陆" other:@"取消"uiViewController:self];
    }

}

- (void)likeAction:(DIYButton *)btn
{
    BmobUser *bUser = [BmobUser getCurrentUser];
    if (bUser)
    {
        
    

    btn.selected = !btn.selected;
    
    PictureModel *picModel = _model.picArray[0];
    
    if (btn.selected)
    {
        
        [[CoreDataMan shareIntance] addEvery:_model.Id imageUrl:picModel.p title:_model.title width:picModel.w height:picModel.h];
        
    }
    else
    {
        [[CoreDataMan shareIntance]deleteEveryWithId:_model.Id];
    }
        
        }
    else
    {
        [CallTool alertActionWithTitle:@"提示" message:@"还没有登陆哦,请先登陆" other:@"取消" uiViewController:self];
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        return [CollectionDetailTableViewCell heightForCell:self.model tag:2000];
    }
    else if (indexPath.section == 1)
    {
        if (self.model.productArray.count != 0)
        {
            ProductModel *model = self.model.productArray[indexPath.row];
            return [ShopTableViewCell heightForCell:model];
        }
        return 0;
    }
    else
    {
        return 100;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1)
    {
        WebViewController *web = [[WebViewController alloc]init];
        if (self.model.productArray.count != 0)
        {
            ProductModel *model = self.model.productArray[indexPath.row];
            web.url = model.url;
            [self.navigationController pushViewController:web animated:NO];
        }
    }
    else if (indexPath.section == 2)
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *report = [UIAlertAction actionWithTitle:@"举报" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [CallTool alertActionWithTitle:@"提示" message:@"举报成功" other:@"取消" uiViewController:self];
            
        }];
        [alert addAction:cancel];
        [alert addAction:report];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

- (void)rightBtnAction:(UIButton *)button
{
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"5668e3bde0f55a90700038ed"
                                      shareText:@"推荐好物, 分享视频 https://itunes.apple.com/cn/app/%e7%b3%96%e5%a6%86/id1068451018?mt=8"
                                     shareImage:[UIImage imageNamed:@"Tango"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToWechatTimeline, UMShareToWechatSession, UMShareToEmail, UMShareToSms,nil] delegate:nil];
}

//实现回调方法（可选）：
-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        //得到分享到的微博平台名
        NSLog(@"share to sns name is %@",[[response.data allKeys] objectAtIndex:0]);
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
